adminz_change_list_table_container=setClassById('adminz_change_list_table_container', 'container table-container');

var $table = $('#adminz_change_list_table')


function getSelectedRows(field_names) {
  var selectedRows = $table.bootstrapTable('getSelections');
  // console.log(selectedRows);
  var selectedData = [];
  for (var i = 0; i < selectedRows.length; i++) {
    var rowData = {};
    for (var j = 0; j < field_names.length; j++) {
      rowData[field_names[j]] = selectedRows[i][field_names[j]];
    }
    selectedData.push(rowData);
  }
  return selectedData
  //alert('getSelections: ' + JSON.stringify(selectedData))
}


function calculateErrorCount(editor) {
    var annotations = editor.getSession().getAnnotations();
    var errorCount = annotations.filter(function(annotation) {
        return annotation.type === "error";
    }).length;
    return errorCount;
}


// trigger extension
ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/json");
editor.setTheme("ace/theme/tomorrow");
// enable autocompletion and snippets
editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: false
});

$(document).ready(function() {
    // 从Django模板变量中获取JSON字符串，并解析为JavaScript对象
    var csrf_token = $('#csrf_token').val(); // 获取 CSRF 令牌
    var selected_action_name = $('#adminz_change_list_action_selector').val();
    var action_and_info = JSON.parse(document.getElementById('container_for_action_and_info').textContent);
    // console.log(action_and_info)
    var field_names = JSON.parse(document.getElementById('container_for_field_names').textContent);
    var default_action_name = $('#adminz_change_list_action_selector').val();
    editor.setValue(JSON.stringify(action_and_info[default_action_name].param, null, 2), -1);



    $('#adminz_change_list_action_selector').on('change', function() {
        selected_action_name = $(this).val();
        // console.log(selected_action_name)
        // console.log(action_and_info[selected_action_name])
        editor.setValue(JSON.stringify(action_and_info[selected_action_name].param, null, 2), -1);
    });

    editor.on('change', function() {
        try {
            // 尝试将当前内容解析为 JSON 对象
            var tmpvar = JSON.parse(editor.getValue());
            action_and_info[selected_action_name]["param"] = tmpvar
        } catch (e) {
            // 如果解析失败，可以在这里处理错误
            // console.error("Invalid JSON:", e);
        }
    });

    $('#adminz_change_list_table_button_run_action').on('click', function() {

        // console.log(selected_action_name)
        // console.log(action_and_info[selected_action_name].param)
        getSelectedRows(field_names)
        jsonData = {
            "param": action_and_info[selected_action_name].param,
            "records": getSelectedRows(field_names)
        }

        $.ajax({
            url: action_and_info[selected_action_name].action_url,
            type: 'POST',
            data: JSON.stringify(jsonData),
            contentType: 'application/json;charset=UTF-8',
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader('X-CSRFToken', csrf_token); // 设置 CSRF 令牌
            },
            success: function(response) {
                // 请求成功时的处理
                console.log(response);
            },
            error: function(xhr, status, error) {
                // 请求失败时的处理
                console.error(error);
            }
        });
    });

 });


